package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;

import java.util.List;

import com.itheima.dao.MenuDao;

import com.itheima.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单管理
 */
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;


    @Override
    //新增菜单
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    @Override
    //分页
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//ThreadLocal
        PageHelper.startPage(currentPage, pageSize);//分页插件，会在执行sql之前将分页关键字追加到SQL后面
        Page<Menu> page = menuDao.findByCondition(queryString);
        if (page != null) {
            for (Menu menu : page) {
                if (menu.getLevel() == 1) {
                    menu.setHasChildren(true);
                }
            }
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<Menu> findParentId() {
        return menuDao.findParentId();
    }

    public void edit(Menu menu) {
        menuDao.edit(menu);
    }

    @Override
    public void delete(Integer id) {
        menuDao.deleteById(id);

    }

    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    @Override
    public List<Menu> findMenuByUserName(String username) {
        int role_id = menuDao.findUserId(username);
        List<Integer> menuByRoleId = menuDao.findMenuIdByRoleId(role_id);
        List<Menu> list = new ArrayList<>();

        for (Integer id : menuByRoleId) {
            Menu parent = menuDao.findParentMenu(id);
            if (parent != null) {
                List<Menu> childrensByParentId = menuDao.findChildrensByParentId(id);
                parent.setChildren(childrensByParentId);
                list.add(parent);
            }
        }


        return list;


    }

    @Override
    public List<Menu> findAll() {

        return menuDao.findAll();

    }

    @Override
    public List<Menu> findChildrensByParentId(int id) {

        return menuDao.findChildrensByParentId(id);

    }

    @Override
    public List<Menu> getSonMenuByID(String name) {
        Menu menu = menuDao.findMenuIdByName(name);
        List<Menu>menuList=menuDao.getSonMenuByID(menu.getId());
        return menuList;
    }
}
